<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\model\admin\User as UserModel;
use app\admin\service\admin\User as AdminUserService;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

/**
 * 超管后台认证
 * Class Passport
 * @package app\store\controller
 */
class Passport extends Controller
{
    /**
     * 强制验证当前访问的控制器方法method
     * @var array
     */
    protected $methodRules = [
        'login' => 'POST',
    ];

    /**
     * 超管后台账号登录
     * @return array|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function login()
    {
        // 超管后台用户登录
        $model = new UserModel;
        if (($userInfo = $model->login($this->postData())) === false) {
            return $this->renderError($model->getError() ?: '登录失败');
        }
        return $this->renderSuccess([
            'userId' => $userInfo['admin_user_id'],
            'token' => $model->getToken()
        ], '登录成功');
    }

    /**
     * 超管后台手机登录
     * @return array|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function phonelogin()
    {
        // 超管后台用户登录
        $model = new UserModel;
        if (($userInfo = $model->phonelogin($this->postData())) === false) {
            return $this->renderError($model->getError() ?: '登录失败');
        }
        return $this->renderSuccess([
            'userId' => $userInfo['admin_user_id'],
            'token' => $model->getToken()
        ], '登录成功');
    }

    /**
     * 重置密码
     * @return array|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function resetPassword()
    {
        // 超管后台用户登录
        $model = new UserModel;
        if (($model->resetPassword($this->postData())) === false) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('提交成功，前往登录...');
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        // 清空登录状态
        AdminUserService::logout();
        return $this->renderSuccess('操作成功');
    }

    public function sendSms($mobile, $model)
    {
        $code = sendSms($mobile);
        // 记录验证码，保存5分钟
        Cache::set($model . $mobile . 'smscode', $code, 60 * 5);
        return $this->renderSuccess('发送成功，请留意手机短信');
    }

}
